package com.wjx.dingcan.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.kzw.core.orm.Page;
import com.kzw.core.orm.PageRequest;
import com.kzw.core.orm.StringPropertyFilter;
import com.kzw.core.util.ContextUtil;
import com.kzw.core.util.ExtjsUtil;
import com.kzw.core.web.action.BaseAction;
import com.kzw.oa.model.system.AppUser;
import com.kzw.oa.util.JSON;
import com.wjx.dingcan.model.Food;
import com.wjx.dingcan.service.FoodService;

@Controller
@Scope("prototype")
public class FoodAction extends BaseAction {
	
	@Autowired
	private FoodService foodService;
	
	/**
	 * 显示列表, ok
	 */
	public String list() {
		HttpServletRequest request = getRequest();
		/*
		 *Page extended PageRequest.
		 * EXtjsUtil.getPageReq(request) wrap the pageRequest from request params. 
		 */
		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);

		Page<Food> page = foodService.search2(pageRequest, filters);
	
		jsonString = new JSON(page).buildWithFilters(3);
		return SUCCESS;
	}
	
	/**
	 * list current food submited. 
	 * ok
	 * */
	public String listMy() {
		HttpServletRequest request = getRequest();

		AppUser currentUser = ContextUtil.getCurrentUser();
		
		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);
		//spreak it detail.
		filters.add(new StringPropertyFilter("EQL_owner.userId", currentUser.getUserId() + ""));
		
		Page<Food> page = foodService.search2(pageRequest, filters);
	
		jsonString = new JSON(page).buildWithFilters(3);
		return SUCCESS;
	}
	
	/**
	 * get food by id. 
	 * ok
	 * */
	public String getById() {
		HttpServletRequest request = getRequest();
		
		String oid = request.getParameter("oid");
		
		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);
		//spreak it detail.
		filters.add(new StringPropertyFilter("EQL_oid", oid));
	 
		Page<Food> page = foodService.search2(pageRequest, filters);
	
		jsonString = new JSON(page).buildWithFilters(3);
		return SUCCESS;
	}
	
	/**
	 * 通过ids来查找food
	 * */
	public String find() {
		HttpServletRequest request = getRequest();
		
		String ids = request.getParameter("ids");
		if(ids == null || ids.equals("")) {
			return SUCCESS;
		}
		
		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);
		
		List<Food> foods = foodService.findByIds(ids);
		jsonString = new JSON(foods).buildWithFilters(3);
		return SUCCESS;
	}
	
	/**
	 * 增加food
	 * foodName
	 * foodPrice
	 * yunfei
	 * description
	 * pics
	 * */
	@SuppressWarnings("unchecked")
	public String add() {
		HttpServletRequest request = getRequest();

		Food food= new Food();
		AppUser currentUser = ContextUtil.getCurrentUser();
		food.setOwner(currentUser);
		List<String> pics = new ArrayList<String>();
//		ContextUtil.
		String rootPath = ServletActionContext.getServletContext().getRealPath("/htmls");
		String savePath = rootPath + "/upload"; 
		String tempPath = rootPath + "/temp";
		File tempFile = new File(tempPath);
		if(!tempFile.exists()) {
			tempFile.mkdir();
		}
		
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(1024 * 100);
		factory.setRepository(tempFile);
		ServletFileUpload upload = new ServletFileUpload(factory);
		
		//解决上传文件名的中文乱码
		upload.setHeaderEncoding("utf-8");
		if(!ServletFileUpload.isMultipartContent(request)) {
			return "{\"success\":\"false\", \"msg\":\"not is multipartcontent\"}" ;
		}
		
		try {
			List<FileItem> list = upload.parseRequest(request);
			for(FileItem item : list) {
				if(item.isFormField()) {
					String name = item.getFieldName();
					String value = item.getString("utf-8");
					System.out.println(name + "=" + value);
					if(name.equals("foodName")) {
						food.setFoodName(value);
					} else if(name.equals("foodPrice")) {
						food.setFoodPrice(Float.parseFloat(value));
					} else if(name.equals("yunfei")) {
						food.setYunfei(Float.parseFloat(value));
					} else if(name.equals("description")) {
						food.setDescription(value);
					}
				} else { //如果filtItem中封装的是文件
					String fileName = item.getName();
					if(fileName == null || 
							fileName.trim().equals("")) {
						return "{\"success\":\"false\", \"msg\":\"picture file name is error\"}";
					}
					
					String fileExtName = fileName.substring(fileName.lastIndexOf(".") + 1);
					InputStream is = item.getInputStream();
					String saveFilename = UUID.randomUUID().toString() + "." + fileExtName;
					File pic = new File(savePath, saveFilename);
					pics.add("upload/" + saveFilename);
					FileOutputStream fos = new FileOutputStream(pic);
					byte[] buf = new byte[1024];
					int len = 0;
					while((len = is.read(buf)) > 0) {
						fos.write(buf, 0, len);
					}
					is.close();
					fos.close();
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
		food.setPics(pics);

		foodService.saveOrUpdate(food);
		
		return SUCCESS;
	}
	
	
	/**
	 * 删除多条食品记录
	 * 
	 * */
	public String multDel() {
		
		HttpServletRequest request = getRequest();
		
		String ids = request.getParameter("ids");
		if(ids == null) {
			return "{\"success\": \"true\",\"msg\":\"delete 0 item\"}";
		}
		String[] idsArr = ids.split(",");
		foodService.remove(idsArr, true);
		
		try {
			getResponse().sendRedirect("/dingcan/htmls/merchant_user_center.html");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	


}
